import { signature } from './../utils/signature';
import AppointOrderModel from "../model/appointOrder";
import PalaceUserModel from '../model/palaceUser';
import { createOrder, merchantParkTicketGridNew } from './../thirdServices/palaceApi';
import log from '../utils/log';

class PalaceHelper {
  async buy(poolVO, touristList: any[]) {
    const user: any = await this.getCreateUser();
    if (user) {
      const ticketList = await this.getModelCodeList(poolVO.occDate, this.grouping(touristList));
      try {
        const isBuy = await this.createOrder(ticketList, poolVO, user);
        if (isBuy) {
          await this.addOrder(user.phone, poolVO, touristList);
        }
        return isBuy;   
      } catch (error) {
          console.log(error)
      }
    } else {
      log.debug('【故宫】：没有可用购票用户');
    }
    
    return false;
  }

  grouping(touristList) {
    // const type = ['标准票', '老年人票', '未成年人免费票', '学生票'];
    // tickType
    const standardList: any = [];
    const elderlyList: any = [];
    const minorList: any = [];
    const studentList: any = [];
    
    touristList.forEach(item => {
      if (item.ticketType === '标准票') {
        standardList.push({
          realName: item.name,
          certType: Number(item.idType),
          certNo: item.idNo
        });
      } else if (item.ticketType === '老年人票') {
        elderlyList.push({
          realName: item.name,
          certType: item.idType,
          certNo: item.idNo
      });
      } else if (item.ticketType === '未成年人免费票') {
        minorList.push({
          realName: item.name,
          certType: item.idType,
          certNo: item.idNo
      });
      } else if (item.ticketType === '学生票') {
        studentList.push({
          realName: item.name,
          certType: item.idType,
          certNo: item.idNo
        });
      }
    });

    const newList: any[] = [];
    if (standardList.length) {
      newList.push({
        tickType: '标准票',
        orderCertAuthList: standardList,
      });
    }

    if (elderlyList.length) {
      newList.push({
        tickType: '老年人票',
        orderCertAuthList: elderlyList,
      });
    }

    if (minorList.length) {
      newList.push({
        tickType: '未成年人免费票',
        orderCertAuthList: minorList,
      });
    }

    if (studentList.length) {
      newList.push({
        tickType: '学生票',
        orderCertAuthList: studentList
      });
    }
    return newList;
  }

  async getModelCodeList(date, touristList) {
    const params = {
      date, 
      merchantParkInfoId: 11324,
      currPage: 1,
      pageSize: 200,
      merchantInfoId: 2655,
      playDate: date,
      businessType: 'park'
    };
    try {
      const res = await merchantParkTicketGridNew(params);
      if (res.data.status === 200) {
        const ticketList = res.data.data[0].ticketList;
        const list = touristList.map(item => {
          const obj = ticketList.find(ticket => ticket.nickName);
          return {
            ...item,
            modelCode: obj.modelCode,
            itemId: obj.itemId,
            ticketName: obj.modelName,
            price: obj.price
          };
        });

        return list;
      }
    } catch (error) {
      console.log(error)
    }
  }

  addOrder(buyUser, poolVO, touristList) {
    // 添加订单
    const orderInfo = {
      createUser: buyUser,
      appointDate: poolVO.occDate,
      appointTime: poolVO.hallScheduleId,
      touristInfo: JSON.stringify(touristList),
      platform: 2,
    };
    try {
      AppointOrderModel.insert(orderInfo); 
    } catch (error) {
      
    }
  }

  async getCreateUser() {
    try {
      const model = await PalaceUserModel.findOneAvailable();
      if (model) {
        const user = {
          userId: model.getDataValue('uuid'),
          token: model.getDataValue('accessToken'),
          phone: model.getDataValue('phonenumber'),
          openId: model.getDataValue('openId'),
          mpDeviceToken: model.getDataValue('mpDeviceToken')
        }
        return user;
      }
    } catch (error) {
      console.log(error);
    }
    return null;
  }

  async createOrder(ticketList, poolVO, user: any) {
    const params = signature(user.token, '' + Date.now());
    const fsTimeRange = poolVO.DTO.fsTimeRange.split('~');
    const saveOrders = ticketList.map(item => {
      return {
        ticketName: item.ticketName,
        price: item.price,
        amount: item.orderCertAuthList.length,
        modelCode: item.modelCode,
        itemId: item.itemId,
        wayType: '6',
        fsName: poolVO.DTO.fsTimeName,
        orderCertAuthList: item.orderCertAuthList,
        needConfirm: 'F' ,
        spiltStartTime: fsTimeRange[0].trim(),
        spiltEndTime: fsTimeRange[1].trim()
      }
    });
    const buyUser = saveOrders[0].orderCertAuthList[0];
    const data = { 
      buyer: {
        id: user.userId,
        openId: user.openId,
        mobile: user.phone,
        credentialNo: buyUser.certNo,
        credentialType: `${buyUser.certType}`,
        nickName: buyUser.realName
      },
      couponCode: '',
      startDate: poolVO.occDate,
      endDate: poolVO.occDate, 
      addTickets: [], 
      saveOrders,
      wayType: '6',
      orderType: 'park',
      merchantInfoId: '2655'
    };
    try {
      const orderinfo = await createOrder(user.token, params, data, user.openId, user.mpDeviceToken);
      if (orderinfo.data.code === 200) {
        return true;
      } else {
        console.log(orderinfo.data)
      }
    } catch (error) {
      console.log(error.response.data);
    }

    return false;
  }
}

export default PalaceHelper;